package com.aloda.ojgateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.aloda.ojgateway.properties.InnerProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * @Author aloda
 * @Date 2025/4/28 14:15
 */
@Component
public class InnerGlobalFilter implements GlobalFilter, Ordered {

    @Resource
    private InnerProperties innerProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        // 1.判断是否放行路径
        if (isExclude(path)) {
            // 无需拦截，直接放行
            return chain.filter(exchange);
        }
        // 2.判断路径中是否包含 inner，只允许内部调用
        if (antPathMatcher.match("/**/inner/**", path)) {
            // 拦截，设置响应状态码为401
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 7.放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 利用spring的AntPathMatcher判断路径是否为拦截路径
     *
     * @param path
     * @return
     */
    private boolean isExclude(String path) {
        for (String excludePath : innerProperties.getExcludePaths()) {
            if (antPathMatcher.match(excludePath, path)) {
                return true;
            }
        }
        return false;
    }
}
